# -*- coding: utf-8 -*-
import os
import sys

import pandas as pd
import winreg

from PyQt5.QtGui import QIntValidator
from PyQt5.QtWidgets import QWidget, QApplication, QFormLayout, QLabel, QLineEdit, QFileDialog, QPushButton, \
    QMessageBox, QMainWindow

key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders')
desktop_path = winreg.QueryValueEx(key, "Desktop")[0]
# print(desktop_path)
workdir = os.path.join(desktop_path, "合并")


def hebing(workdir, head, dele):
    if not os.path.exists(workdir):
        print("未找到工作文件夹，请新建后重试！")
        return False, "未找到工作文件夹，请新建后重试！"
    else:
        fs = os.listdir(workdir)
        fs = [os.path.join(workdir, i) for i in fs if not i.startswith("~")]

        # head=input("输入标题行数:")
        head = 0 if not head else int(head)
        # dele=input("是否删除合并前文件？(y/n)")
        dele = "n" if not dele else dele
        r = []
        for f in fs:
            if f == "合并.xlsx":
                continue
            if not (f.endswith(".xlsx") or f.endswith(".xls")):
                continue
            d = pd.read_excel(f, header=head, dtype=str)
            r.append(d)
            if dele != 'n':
                os.remove(f)

        def acc(a):
            if len(a) <= 2:
                return [pd.concat(a)]

            mid = len(a) // 2
            left = a[:mid]
            right = a[mid:]

            R1 = acc(left)
            print(len(R1))
            R2 = acc(right)
            print(len(R2))
            return acc(R1 + R2)

        if len(r) > 0:
            res = acc(r)[0]
            # print(len(res))
            res.to_excel(os.path.join(workdir, "合并.xlsx"), index=False)
            return True, ""
        else:
            print("无excel 文件")
            return False, "无excel 文件"


class gui(QWidget):
    def __init__(self, *args, **kwargs):
        super(gui, self).__init__(*args, **kwargs)
        self.setWindowTitle("excel合并")
        self.setFixedWidth(300)
        layout = QFormLayout(self)

        self.rowinput = QLineEdit()
        self.rowinput.setPlaceholderText("输入整数数字，最大999")
        pIntValidator = QIntValidator(self)
        pIntValidator.setRange(1, 999)
        self.rowinput.setValidator(pIntValidator)

        self.dirSet = QLineEdit()
        self.dirSet.setReadOnly(True)
        self.dirSet.setText(workdir)

        self.chdirbtn = QPushButton()
        self.chdirbtn.setText("修改工作路径")

        self.startbtn = QPushButton()
        self.startbtn.setText("开始合并!")

        layout.addRow(QLabel("标题行数"), self.rowinput)
        layout.addRow(QLabel("工作路径"), self.dirSet)
        layout.addRow(self.chdirbtn)
        layout.addRow(self.startbtn)

        self.chdirbtn.clicked.connect(self.chdir)
        self.startbtn.clicked.connect(self.start)

    def chdir(self):
        directory = QFileDialog.getExistingDirectory(self, "打开", "C:/")
        # 在状态栏显示文件地址
        # self.statusbar.showMessage(file)
        self.dirSet.setText(directory)

    def start(self):
        row = self.rowinput.text()
        # print(row)
        if not row:
            QMessageBox.warning(self,"", "未输入行数！")
        else:
            directory = self.dirSet.text()

            result, info = hebing(directory, row, False)
            if result:
                QMessageBox.information(self,"结果", "成功！请去工作路径查看合并结果")
            else:
                QMessageBox.critical(self,"结果", f"失败！{info}")



if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = gui()
    w.show()
    sys.exit(app.exec())
